package com.jiangnan.service.Impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.jiangnan.mapper.ClazzMapper;
import com.jiangnan.pojo.Clazz;
import com.jiangnan.pojo.ClazzQueryParam;
import com.jiangnan.pojo.PageResult;
import com.jiangnan.service.ClazzService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;

@Service
public class ClazzServiceImpl implements ClazzService {

    @Autowired
    private ClazzMapper clazzMapper;

    @Override
    public PageResult<Clazz> page(ClazzQueryParam clazzQueryParam) {
        // 1. 设置分页参数
        PageHelper.startPage(clazzQueryParam.getPage(), clazzQueryParam.getPageSize());
        // 2. 执行查询语句
        List<Clazz> clazzList = clazzMapper.getPage(clazzQueryParam);
        clazzList.forEach(clazz -> {
            if (LocalDate.now().isBefore(clazz.getBeginDate())){
                clazz.setStatus("未开班");
            } else if (LocalDate.now().isAfter(clazz.getEndDate())) {
                clazz.setStatus("已结课");
            }else {
                clazz.setStatus("在读");
            }
        });
        // 3. 解析查询结果，封装为 PageResult 对象并返回
        Page<Clazz> p = (Page<Clazz>) clazzList;
        return new PageResult<>(p.getTotal(), p.getResult());
    }

    @Override
    public void deleteById(Integer id) {
        clazzMapper.deleteById(id);
    }

    @Override
    public void save(Clazz clazz) {
        // 1. 设置创建时间
        clazz.setCreateTime(LocalDateTime.now());
        clazz.setUpdateTime(LocalDateTime.now());
        // 2. 保存班级信息
        clazzMapper.insert(clazz);
    }

    @Override
    public Clazz getById(Integer id) {
        Clazz clazz = clazzMapper.getById(id);
        return clazz;
    }

    @Override
    public void update(Clazz clazz) {
        clazz.setUpdateTime(LocalDateTime.now());
        clazzMapper.update(clazz);
    }

    @Override
    public List<Clazz> list() {
        List<Clazz> clazzList = clazzMapper.getPage(null);
        return clazzList;
    }
}
